package com.demo.controller.article;

import com.demo.controller.media.MediaAdminService;
import com.demo.model.Article;
import com.demo.model.Media;
import com.jfinal.plugin.cron4j.ITask;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.List;

import static com.demo.controller.article.TakeArticleUtil.uploadHeadImg;


/**
 * @Auther: 10091
 * @Date: 2018-07-14 13:54
 * @Description:
 *
 * 火星财经作者http://www.huoxing24.com/author
 */
public class ArticleUpdateTask implements ITask {

    static Logger logger  =  Logger.getLogger(ArticleUpdateTask.class);
    ArticleAdminService ser = ArticleAdminService.me;
    MediaAdminService mediaService = MediaAdminService.me;


    @Override
    public void stop() {
        doTask();
    }

    @Override
    public void run() {
        doTask();
    }

    private void doTask(){
        logger.debug("start article task.");
        //先查询出待更新的媒体号
        List<Media> medias = mediaService.findAllNoLock();
        for (Media ls :medias){
            loadArticle(ls);
        }

    }

    /**
     * 抓取
     * @param media
     * @return
     */
    private void loadArticle(Media media){

        Document doc = null;
        try {
            doc = Jsoup.connect(media.getTakeUrl()).get();
            //doc = Jsoup.connect("http://en.wikipedia.org/").get();
            //Elements newsHeadlines = doc.select("#mp-itn b a");
            Elements newsHeadlines = doc.select("div .index-news-list");
            logger.debug(newsHeadlines.size());
            for (Element headline : newsHeadlines) {
                Article article = new Article();
                article.setMediaId(media.getId());
                // logger.debug(headline.attr("title")+"----"+headline.absUrl("href") );
                // logger.debug(headline.attr("title")+"----"+headline.absUrl("href") );

                //标题
                Elements titles = headline.select("div .list-left a");
                if (titles.size()>0){
                    String _title = titles.get(0).attr("title");
                    //logger.debug("title:"+_title);
                    article.setMainTitle(_title);
                    String _url = titles.get(0).absUrl("href");
                    //logger.debug("url:"+_url);
                    article.setOldArticleUrl(_url);
                    Integer num = ser.countArticle(_title);
                    if (num != null && num >0){
                        continue;
                    }
                }

                //image
                Elements images = headline.select("div .list-left img");
                //logger.debug("images1:"+images.get(0).attr("src"));
                if(images.size()>0){
                    String _image = images.get(0).absUrl("src");
                    //logger.debug("images2:"+_image);
                    article.setCoverImage(_image);
                }
                //简介
                Elements details = headline.select("div .details");
                if (!details.isEmpty()){
                   // logger.debug("details:"+details.get(0).html());
                    String _abstract =  details.get(0).html();
                    article.setAbstract(_abstract);
                }
                //跳转详情页获取一下详细信息
                Document detaiDoc =  Jsoup.connect(article.getOldArticleUrl()).get();
                Elements contentElement = detaiDoc.select("div .detail-text-cont.simditor-body");
                String _contents = "";
                if (!contentElement.isEmpty()){
                    //_contents = contentElement.get(0).html();
                   // article.setContents(_contents);
                    Elements pngs = contentElement.select("img[src]");
                    for (Element element : pngs) {
                        String imgUrl = element.attr("src");
                        //if (imgUrl.trim().startsWith("/")) {
                        //imgUrl =HTTPHOST + imgUrl;
                        imgUrl = uploadHeadImg(imgUrl);
                        element.attr("src", imgUrl);
                        // }
                    }
                   // String   newsBody = contentElement.toString();
                    _contents = contentElement.get(0).html();
                }
                ser.save(article,_contents);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
       // logger.debug(doc.title());
    }

}
